// 根据比较基础的uni-app chooseimage和uploadfile重写而成的上传步骤
// 此部分需要混合进页面使用，不要当作工具类调用
// 2022.12.7由于保存了太多了obj对象，导致系统卡死
import {mapActions, mapState} from "vuex";
import limitUpload from '../network/asyncRequest'
import language from "../../api/language";
import middleWareService from "../../api/modules/middleWareService";

export default {
    computed: {
        ...mapState('user', ['userInfo']),
        ...mapState('componentCommunicate', ['clickUpload'])
    },
    data(){
        return {
            segUploadToken: '',
            segUploadTotal: {  // 特殊的结构，监控整体信息
                total: 0,
                success: 0,
                fail: 0
            },
            segUploadErrorList: [],  // 失败的对象存储
            segUploadStatusList: [],  // 成功对象存储
            segUploadStatusDict: {}  // 用于渲染
        }
    },
    methods: {
        ...mapActions({
            updateUploadState: 'componentCommunicate/setClickUpload'
        }),
        // upload 2 java
        uploadImgListToMiddleWare(){
            // 这部分导致需要后续优化
            // 重传以后，会再次上传整个列表，应该只上传一个文件
            let d = this.segUploadTotal
            if(d.success + d.fail === d.total){
                let imgList = []
                for(let i = 0; i < this.segUploadStatusList.length; i++){
                    let m = this.segUploadStatusList[i]
                    imgList.push(m.name)
                }
                middleWareService.historyInsert(this.userInfo.userName, this.segUploadToken, imgList,
                    (res)=>{ console.log("success")}, (res)=>{ console.log('insert fail')})
            }
        },

        // 防止和界面的函数冲突
        getUploadTranslate(posIndex){
            let langDict = language.getTranslate(language.segUpload)
            if (posIndex === 0){
                return langDict.uploadError
            }else if(posIndex === 1){
                return langDict.uploadOpenError
            }
        },
        segReUpload(monitor){
            // 防止出现进度条大于100
            this.segUploadTotal.fail -= 1
            // 深拷贝
            let _tmp = JSON.stringify(monitor)
            let copyMonitor = JSON.parse(_tmp)
            for(let i = 0; i < this.segUploadErrorList.length; i++){
                let eachMonitor = this.segUploadErrorList[i]
                if(eachMonitor.id === monitor.id){
                    this.segUploadErrorList.splice(i, 1)
                    break
                }
            }
            delete this.segUploadStatusDict[monitor.id]
            // 送入检测
            this.segUploadFileValidate(copyMonitor)
        },
        segUploadStateClear(){
            // 记录结构体清空
            this.segUploadTotal = {
                total: 0,
                success: 0,
                fail: 0
            }
            this.segUploadErrorList = []
            this.segUploadStatusList = []
            this.segUploadStatusDict = {}
        },
        segUploadFileValidate(monitor) {
            this.segUploadStatusDict[monitor.id] = monitor

            // 验证类的相关代码
            let fileType = monitor.type
            if (fileType.indexOf('image') === -1) {
                monitor.status = 'fail'
                monitor.errorMsg = 'fileObj is not image'
                monitor.path = null
                this.segUploadErrorList.push(monitor)
            } else {
                this.segUpload(monitor)
            }
        },
        segSendToFather(){
            // 发送相关消息到父组建
            this.$emit('uploadStatusUpdate', {
                total: this.segUploadTotal,
                list: this.segUploadStatusList,
                errorList: this.segUploadErrorList,
                token: this.segUploadToken,
                uNameEncode: this.segUploadB64Encode(this.userInfo.userName)
            })
        },
        segUploadTokenGet(){
            let yy = new Date().getFullYear()
            let mm = new Date().getMonth() + 1
            let dd = new Date().getDate()
            let hh = new Date().getHours()
            let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
            let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
            return yy + '_' + mm + '_' + dd + '_' + hh + '_' + mf + '_' + ss
        },
        segUploadB64Encode(str){
            return btoa(encodeURIComponent(str))
        },
        segUpload(monitor){
            // https://uniapp.dcloud.net.cn/api/request/network-file.html
            // 可以通过abort中断上传任务
            let that = this
            let formData = {
                'user_name': this.segUploadB64Encode(this.userInfo.userName),
                'token': this.segUploadToken
            }
            const success = (res) => {
                // 根据服务器的返回信息，查看是否合规
                let validateMsgArray = JSON.parse(res.data).message
                for(let i = 0; i < validateMsgArray.length; i++){
                    let data = validateMsgArray[i]
                    if(data.name === monitor.name){
                        if(data.hasOwnProperty('error')){
                            monitor.status = 'error'
                            monitor.errorMsg = this.getUploadTranslate(0) + "，log: " + JSON.stringify(data)
                            that.segUploadTotal.fail += 1
                            that.segUploadErrorList.push(monitor)
                        }else{
                            monitor.path = ""  // 释放一些缓存
                            monitor.progress = 100
                            monitor.status = 'success'

                            // console.log(res.data)
                            that.segUploadTotal.success += 1
                            that.segUploadStatusList.push(monitor)
                        }
                        break
                    }
                }
            }
            const fail = (res) => {
                monitor.status = 'error'
                monitor.errorMsg = this.getUploadTranslate(0) + "，log: " + JSON.stringify(res)
                that.segUploadTotal.fail += 1
                that.segUploadErrorList.push(monitor)
            }
            limitUpload.PostFileAsync(monitor, formData, success, fail).then(res => {
                that.segSendToFather()
                that.uploadImgListToMiddleWare()
            })
        },
        segUploadFile(){
            this.segUploadToken = this.segUploadTokenGet()
            let that = this
            let first = true
            uni.chooseImage({
                count: 500, //默认9
                sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], //从相册选择
                success: function (res) {
                    if(first){
                        // that.segUploadStateClear()
                        first = false

                        // 优化体验
                        that.segUploadStateClear()
                        that.show = true
                        that.updateUploadState(!that.clickUpload)
                    }

                    // console.log(JSON.stringify(res.tempFilePaths));
                    // debugger
                    let fileArray = res.tempFiles
                    that.segUploadTotal.total = fileArray.length
                    for(let index=0; index < fileArray.length; index++){
                        let file = fileArray[index]
                        let fileMonitor = {
                                // 用于快速区分对象，方便重传，重传只要把这个monitor对象segUpload函数就行
                                // 重传的时候记得fail - 1
                                id: index,
                                name: file.name,  // 名字
                                path: file.path,  // 内存File对象
                                type: file.type,  // 文件类型
                                progress: 0,  // 百分比
                                status: 'uploading',  // 回调的执行状态执行状态
                                errorMsg: ''  // 错误信息
                        }
                        // that.segUploadStatusList.push(fileMonitor)
                        that.segUploadFileValidate(fileMonitor)
                    }
                },
                fail: function (res){
                    uni.showModal({
                        title: 'Error',
                        content: this.getUploadTranslate(1) + "，log: " + JSON.stringify(res),
                        showCancel: false
                    })
                },
                complete: function (res){
                    // console.log('complete', res)
                }
            });
        },
        async segUploadClick(){
            this.segUploadFile()
        }
    }
}
